#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

#define INTERACTIVE			0
#define NONINTERACTIVE	1

void help()
{
	printf("Usage : ./client -e [query]\n");
}

int main (int argc, char **argv)
{
	int sockfd;
	int clilen;
	struct sockaddr_un serveraddr; 
	char bufin[1024];
	char formatstr[1024];
	int opt,i;
	int type = INTERACTIVE;
	char seperator[8] = {0x00,};

	sprintf(seperator, "\t");
	while((opt = getopt(argc, argv, "he:s:")) != -1)
	{
		switch(opt)
		{
			case 's':
				sprintf(seperator, "%s", optarg);
				break;
			case 'h':
				help();
				break;
			case 'e':
				type = NONINTERACTIVE;
				memset(bufin, 0x00, sizeof(bufin));
				memcpy(bufin, optarg, strlen(optarg));
				break;
		}
	}

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sockfd < 0)
	{
		perror("Socket error :");
		exit(0);
	}

	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sun_family = AF_UNIX;
	strcpy(serveraddr.sun_path, "/tmp/jstg");
	clilen = sizeof(serveraddr);

	if (connect(sockfd, (struct sockaddr *)&serveraddr, clilen))
	{
		perror("Connect error");
		exit(1);
	}

	while(1)
	{
		if (type == INTERACTIVE)
		{
			printf("JSTG > ");
			memset(bufin, 0x00, sizeof(bufin));	
			fgets(bufin, 1023, stdin);
		}
		if(write(sockfd, bufin, 1024) <= 0)
		{
			perror("Write Error");
			exit(0);
		}
		if(read(sockfd, bufin, 1024) <= 0)
		{
			perror("Read Error");
			exit(0);
		}
		memset(formatstr, 0x00, sizeof(formatstr));
		for (i = 0; i < strlen(bufin); i++)
		{
			if(bufin[i] == '\t')
				strcat(formatstr, seperator);
			else
				formatstr[i] = bufin[i];
		}
		printf("%s\n", formatstr);
		if (type == NONINTERACTIVE)
		{
			write(sockfd, "quit\n", 1024);
			close(sockfd);
			break;
		}
	}
}
